package com.hema.auction.activity;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hema.auction.R;
import com.hema.auction.adapter.BidRecordAdapter;
import com.hema.auction.adapter.FragAdapter;
import com.hema.auction.base.BaseActivity;
import com.hema.auction.bean.BidRecordInfo;
import com.hema.auction.bean.GoodsInfo;
import com.hema.auction.event.TabIndexEvent;
import com.hema.auction.fragment.GoodDetailFragment;
import com.hema.auction.http.HttpTag;
import com.hema.auction.http.biz.HttpManager;
import com.hema.auction.listener.OnScrollChangeListener;
import com.hema.auction.utils.Constant;
import com.hema.auction.utils.GlideUtils;
import com.hema.auction.utils.Utils;
import com.hema.auction.widget.view.DetailPrice;
import com.hema.auction.widget.view.FloatDetailPrice;
import com.hema.auction.widget.view.PagerScrollView;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.bgabanner.BGABanner;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

import static com.hema.auction.R.id.ll_price;
import static com.hema.auction.R.id.tv_bid_record;

/**
 * 商品详情页面
 * author by john
 */
public class GoodsDetailsActivity extends BaseActivity {


    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_home)
    ImageView ivHome;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_message)
    ImageView ivMessage;
    @BindView(R.id.title_view)
    RelativeLayout titleView;
    @BindView(R.id.banner)
    BGABanner banner;
    @BindView(R.id.iv_dear)
    ImageView ivDear;
    @BindView(ll_price)
    DetailPrice llPrice;
    @BindView(R.id.tv_goods_title)
    TextView tvGoodsTitle;
    @BindView(R.id.tv_tips)
    TextView tvTips;
    @BindView(tv_bid_record)
    TextView tvBidRecord;
    @BindView(R.id.rv_bid_record)
    RecyclerView rvBidRecord;
    @BindView(R.id.tv_consume)
    TextView tvConsume;
    @BindView(R.id.iv_consume)
    ImageView ivConsume;
    @BindView(R.id.tv_accumulated_expenditure)
    TextView tvAccumulatedExpenditure;
    @BindView(R.id.ll_accumulated_expenditure)
    LinearLayout llAccumulatedExpenditure;
    @BindView(R.id.tv_starting_price)
    TextView tvStartingPrice;
    @BindView(R.id.tv_fare_increase)
    TextView tvFareIncrease;
    @BindView(R.id.tv_service_charge)
    TextView tvServiceCharge;
    @BindView(R.id.tv_auction_countdown)
    TextView tvAuctionCountdown;
    @BindView(R.id.tv_differential_purchase)
    TextView tvDifferentialPurchase;
    @BindView(R.id.tv_refund_ratio)
    TextView tvRefundRatio;
    @BindView(R.id.tablayout)
    TabLayout tablayout;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.scrollView)
    PagerScrollView scrollView;
    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    @BindView(R.id.float_price)
    FloatDetailPrice floatPrice;
    @BindView(R.id.ll_bottom)
    View llBottom;
    @BindView(R.id.et_coin)
    EditText etCoin;
    @BindView(R.id.ll_differential_purchase)
    View llDifferentialPurchase;
    @BindView(R.id.ll_offer)
    View llOffer;
    @BindView(R.id.tv_next_issue)
    View tvNextIssue;
    @BindView(R.id.tv_end)
    View tvEnd;
    @BindView(R.id.tv_collection)
    TextView tvCollection;
    @BindView(R.id.ll_progress)
    View llProgress;
    @BindView(R.id.progress_offer)
    ProgressBar progressOffer;
    @BindView(R.id.tv_auto_offer)
    TextView tvAutoOffer;
    @BindView(R.id.tv_auto_coin_unit)
    TextView tvAutoCoinUnit;
    @BindView(R.id.tv_offer_price)
    TextView tvOfferPrice;
    @BindView(R.id.ll_newsest)
    View llNewsest;
    @BindView(R.id.iv_notice_pic)
    CircleImageView ivNoticepic;
    @BindView(R.id.tv_notice_content)
    TextView tvNoticeContent;
    private int floatPriceY;
    private String[] title = new String[]{"晒单", "往期成交", "竞拍规则"};
    List<Fragment> fragments = new ArrayList<>();
    private List<BidRecordInfo> bidRecordInfos = new ArrayList<>();
    private BidRecordAdapter bidRecordAdapter;
    private GoodsInfo info;
    private int auctionCoin = 1;
    private int postDelayed = 2000;
    private float indexPrice;//当前价格
    private int tolBuytime;
    private int saleStatus; //1表示在拍，2表示竞拍结束
    private String newGoodId;//下一期商品id
    private String indexGoodId;//当前商品id

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_details);
        ButterKnife.bind(this);
        llPrice.setDetailPrice(floatPrice);
        info = getIntent().getParcelableExtra(Constant.EXTRA_GOOD_INFO);
        if (info == null) {
            info = new GoodsInfo();
            info.setId(getIntent().getStringExtra(Constant.EXTRA_GOOD_ID));
        } else {
            llPrice.setTime(Utils.countDown(info.getCountdown()));
        }
        indexGoodId = info.getId();
        setAuctionStatus();
        init();
        HttpManager.getInstance(this).getOneNewest(this);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (saleStatus == 1) {
            getDefaultHandler().postDelayed(auctionLogRun, postDelayed);
        } else {
            HttpManager.getInstance(this).goodDetailInfo(indexGoodId, this);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        getDefaultHandler().removeCallbacks(auctionLogRun);
    }


    private void init() {
        banner.setFocusable(true);
        banner.setFocusableInTouchMode(true);
        banner.requestFocus();
        banner.setLayoutParams(new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, Utils.getDeviceWidth(this) * 4 / 9));
//        ivDear.setLayoutParams(new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, Utils.getDeviceWidth(this) * 4 / 9));
        refreshLayout.setColorSchemeResources(R.color.colorPrimary);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                GoodDetailFragment fragment = (GoodDetailFragment) fragments.get(tablayout.getSelectedTabPosition());
                fragment.refresh(indexGoodId);
                HttpManager.getInstance(GoodsDetailsActivity.this).goodDetailInfo(indexGoodId, GoodsDetailsActivity.this);
                getAuctionLog();
            }
        });
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(true);
                HttpManager.getInstance(GoodsDetailsActivity.this).goodDetailInfo(indexGoodId, GoodsDetailsActivity.this);
            }
        });
        fragments.add(GoodDetailFragment.newInstance(0, indexGoodId));
        fragments.add(GoodDetailFragment.newInstance(1, indexGoodId));
        fragments.add(GoodDetailFragment.newInstance(2, indexGoodId));
        scrollView.setFragments(fragments);
        scrollView.setTabIndex(0);
        for (Fragment fragment : fragments) {
            GoodDetailFragment detailFragment = (GoodDetailFragment) fragment;
            detailFragment.refreshLayout(refreshLayout);
        }
        FragAdapter adapter = new FragAdapter(getSupportFragmentManager(), fragments, title);
        viewPager.setAdapter(adapter);
        tablayout.setupWithViewPager(viewPager);

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                scrollView.setTabIndex(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        llPrice.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        int[] location = new int[2];
                        llPrice.getLocationOnScreen(location);
                        floatPriceY = location[1] - titleView.getHeight() - Utils.getStatusBarHeight(GoodsDetailsActivity.this);
                        llPrice.getViewTreeObserver()
                                .removeGlobalOnLayoutListener(this);
                        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (getRootView().getBottom() - floatPrice.getBottom() - floatPrice.getHeight() - llBottom.getHeight())+Utils.dp2px(GoodsDetailsActivity.this,10));
                        viewPager.setLayoutParams(lp);
                        floatPrice.setVisibility(View.GONE);
                    }
                });
        scrollView.setListener(new OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY >= floatPriceY) {
                    floatPrice.setVisibility(View.VISIBLE);
                } else {
                    floatPrice.setVisibility(View.GONE);
                }
            }
        });

        setTopData();
        etCoin.setText(String.valueOf(auctionCoin));
        scrollView.scrollTo(0, 0);

        showProgressDialog();
        getAuctionLog();
        updateGoodInfo();
    }


    private void updateGoodInfo() {
        if (info != null) {
            tvGoodsTitle.setText(info.getGoodName());
            if (info.getIsOnSale() == 2) {
                ivDear.setVisibility(View.VISIBLE);
            } else {
                ivDear.setVisibility(View.GONE);
            }
            if (info.getIsCollected() == 0) {
                tvCollection.setText("收藏");
                Drawable image = getResources().getDrawable(R.drawable.ic_collection_detail_def);
                image.setBounds(0, 0, image.getMinimumWidth(), image.getMinimumHeight());
                tvCollection.setCompoundDrawables(null, image, null, null);
            } else {
                tvCollection.setText("收藏");
                Drawable image = getResources().getDrawable(R.drawable.ic_collection_sel);
                image.setBounds(0, 0, image.getMinimumWidth(), image.getMinimumHeight());
                tvCollection.setCompoundDrawables(null, image, null, null);
            }

        }
    }


    /**
     * 设置底部竞拍状态
     */
    private void setAuctionStatus() {
        if (info.getIsOnSale() == 2) {
            //竞拍结束
            llPrice.setAuctionEnd();
            ivDear.setVisibility(View.VISIBLE);
            llProgress.setVisibility(View.GONE);
            if (info.getNewGoodId() == null || !info.getNewGoodId().equals("null") || Utils.isEmpty(info.getNewGoodId())) {
                //有下一期
                tvEnd.setVisibility(View.GONE);
                llOffer.setVisibility(View.GONE);
                tvNextIssue.setVisibility(View.VISIBLE);
                getDefaultHandler().removeCallbacks(auctionLogRun);
            } else {
                //竞拍结束，也没有下一期
                llOffer.setVisibility(View.GONE);
                tvNextIssue.setVisibility(View.GONE);
                tvEnd.setVisibility(View.VISIBLE);
                getDefaultHandler().removeCallbacks(auctionLogRun);
            }
        } else {
            //正在竞拍
            llPrice.setAuctionStart();
            tvNextIssue.setVisibility(View.GONE);
            llProgress.setVisibility(View.GONE);
            llOffer.setVisibility(View.VISIBLE);
            getDefaultHandler().removeCallbacks(auctionLogRun);
            getDefaultHandler().postDelayed(auctionLogRun, postDelayed);
        }
    }

    /**
     * 切换为自动出价模式
     *
     * @param leftTimes 剩余次数
     * @param sumTimes  总次数
     */
    private void setAutoOffer(int leftTimes, int sumTimes) {
        if (leftTimes > 0 && sumTimes > 1) {
            llProgress.setVisibility(View.VISIBLE);
            tvNextIssue.setVisibility(View.GONE);
            llOffer.setVisibility(View.GONE);
            progressOffer.setMax(sumTimes);
            progressOffer.setProgress(sumTimes - leftTimes);

            String autoOffer = getString(R.string.automatic_bid, sumTimes - leftTimes, sumTimes);
            SpannableStringBuilder style = new SpannableStringBuilder(autoOffer);
            style.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)), autoOffer.indexOf(String.valueOf(sumTimes - leftTimes)), autoOffer.indexOf(String.valueOf(sumTimes - leftTimes)) + String.valueOf(sumTimes - leftTimes).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            tvAutoOffer.setText(style);
//            String autoOffer = getString(R.string.automatic_bid, sumTimes - leftTimes, sumTimes);
//            tvAutoOffer.setText(autoOffer);
        } else {
            setAuctionStatus();
        }
    }

    private void setTopData() {
        banner.setAdapter(new BGABanner.Adapter() {
            @Override
            public void fillBannerItem(BGABanner banner, View itemView, Object model, int position) {
                ImageView iv = (ImageView) itemView;
                iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
                GlideUtils.load(GoodsDetailsActivity.this, (String) model, iv);
            }
        });
        bidRecordAdapter = new BidRecordAdapter(bidRecordInfos);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvBidRecord.setLayoutManager(layoutManager);
        rvBidRecord.setAdapter(bidRecordAdapter);
    }

    /**
     * 收藏、取消收藏
     */
    private void collect() {
        showProgressDialog();
        if (info.getIsCollected() == 0) {
            HttpManager.getInstance(this).collectGood(info.getId(), this);
        } else {
            HttpManager.getInstance(this).delCollection(info.getId(), this);
        }
    }


    private View getRootView() {
        return ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
    }

    /**
     * 获取出价记录
     */
    private void getAuctionLog() {
        HttpManager.getInstance(this).getAuctionLog(indexGoodId, this);
    }

    @OnClick({R.id.iv_back, R.id.iv_home, R.id.iv_consume, R.id.tv_collection, R.id.tv_customer_service,
            R.id.iv_reduction, R.id.iv_add, R.id.ll_auction, R.id.ll_bid_record, R.id.tv_next_issue})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_home:
                EventBus.getDefault().post(new TabIndexEvent(0));
                screenManager.popAllActivitys(MainActivity.class);
                break;
            case R.id.iv_consume:
                if (llAccumulatedExpenditure.getVisibility() == View.VISIBLE) {
                    ivConsume.setImageResource(R.drawable.ic_arrow_bottom_black);
                    llAccumulatedExpenditure.setVisibility(View.GONE);
                } else {
                    ivConsume.setImageResource(R.drawable.ic_arrow_top_black);
                    llAccumulatedExpenditure.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.tv_collection://收藏
                collect();
                break;
            case R.id.tv_customer_service://客服
                break;
            case R.id.iv_reduction://减少
                auctionCoin = Integer.valueOf(etCoin.getText().toString());
                if (auctionCoin > 1)
                    etCoin.setText(String.valueOf(auctionCoin - 1));
                break;
            case R.id.iv_add://增加
                auctionCoin = Integer.valueOf(etCoin.getText().toString());
                auctionCoin++;
                etCoin.setText(String.valueOf(auctionCoin));
                break;
            case R.id.ll_auction://竞拍
                if (isLogin) {
                    showProgressDialog();
                    int num = Integer.valueOf(etCoin.getText().toString().trim());
                    setAutoOffer(num, num);
                    HttpManager.getInstance(this).doAuction(info.getId(), etCoin.getText().toString().trim(), this);
                    Utils.hideKeyboard(this);
                } else {
                    goLogin();
                }
                break;
            case R.id.ll_bid_record:
                Bundle bundle = new Bundle();
                bundle.putParcelable(Constant.EXTRA_GOOD_INFO, info);
                intentTo(BidRecordActivity.class, bundle);
                break;
            case R.id.tv_next_issue:
                //下一期
//                info.setId(info.getNewGoodId());
//                showProgressDialog();
//                HttpManager.getInstance(this).goodDetailInfo(info.getNewGoodId(), this);
                indexGoodId = info.getNewGoodId();
                refreshLayout.setRefreshing(true);
                GoodDetailFragment fragment = (GoodDetailFragment) fragments.get(tablayout.getSelectedTabPosition());
                fragment.refresh(indexGoodId);
                HttpManager.getInstance(GoodsDetailsActivity.this).goodDetailInfo(indexGoodId, GoodsDetailsActivity.this);
                getAuctionLog();
                break;
        }
    }

    @Override
    protected void onSuccess(HttpTag httpTag, Call call, JSONObject result) {
        super.onSuccess(httpTag, call, result);
        switch (httpTag) {
            case TAG_GOOD_DETAIL_INFO:
                try {
                    if (result.getInt("errcode") == 0) {
                        JSONObject data = result.getJSONObject("data");
                        info = new Gson().fromJson(data.getJSONObject("base_info").toString(), GoodsInfo.class);
                        indexGoodId = info.getId();
                        if (!data.isNull("new_good_id")) {
                            newGoodId = data.getString("new_good_id");
                        } else {
                            newGoodId = "";
                        }
                        info.setNewGoodId(newGoodId);
                        updateGoodInfo();
                        tvStartingPrice.setText(info.getStartPrice());
                        tvServiceCharge.setText(getString(R.string.auto_coin_unit_format, info.getServicePrice())); //手续费
                        String serviceCharge = tvServiceCharge.getText().toString();
                        tvOfferPrice.setText(serviceCharge);
//                        SpannableStringBuilder style = new SpannableStringBuilder(serviceCharge);
//                        style.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)), serviceCharge.indexOf(info.getServicePrice()), serviceCharge.indexOf(info.getServicePrice()) + info.getServicePrice().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//                        tvAutoCoinUnit.setText(style);

                        tvFareIncrease.setText(info.getUpRange());
                        tvAuctionCountdown.setText(getString(R.string.scend_format, info.getTolBuytime()));
                        tvRefundRatio.setText(info.getBackRate());
                        llPrice.setMarktPrice(Utils.priceUnitFormat(this, info.getPrice()));


                        if (info.getIsDifBuy() == 1) {
                            tvDifferentialPurchase.setText("有");
                            llDifferentialPurchase.setVisibility(View.VISIBLE);
                        } else {
                            tvDifferentialPurchase.setText("无");
                            llDifferentialPurchase.setVisibility(View.GONE);
                        }
                        List<String> bannerInfos = new Gson().fromJson(result.getJSONObject("data").getJSONArray("banner").toString(), new TypeToken<List<String>>() {
                        }.getType());
                        banner.setData(bannerInfos, null);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_DO_AUCTION://竞拍
                try {
                    if (result.getInt("errcode") == 0) {
//                        HttpManager.getInstance(this).getAuctionLog(info.getId(), this);
                        getAuctionLog();
                    } else if (result.getInt("errcode") == 0) {

                    }
                    showToastSafe(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_GET_AUCTION_LOG://出价记录
                try {
                    if (result.getInt("errcode") == 0) {
                        if(isFinishing())
                            return;
                        JSONObject data = result.getJSONObject("data");
                        int logCount = data.getInt("log_count");
                        tvBidRecord.setText(getString(R.string.bid_record_format, logCount));
                        int pSumCost = data.getInt("p_sum_cost");
                        int zSumCost = data.getInt("z_sum_cost");
                        tvConsume.setText(getString(R.string.consume_format, pSumCost, zSumCost));
                        tvAccumulatedExpenditure.setText(Utils.priceUnitFormat(this, (pSumCost + zSumCost)));
                        JSONArray jsonArray = result.getJSONObject("data").getJSONArray("log");
                        if (jsonArray.length() == 0) {
                            tvTips.setVisibility(View.GONE);
                        } else {
                            tvTips.setVisibility(View.VISIBLE);
                        }
                        bidRecordInfos.clear();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            if (i == 3)
                                break;
                            BidRecordInfo bidRecordInfo = new Gson().fromJson(jsonArray.get(i).toString(), BidRecordInfo.class);
                            bidRecordInfos.add(bidRecordInfo);
                        }

                        bidRecordAdapter.setNewData(bidRecordInfos);

                        saleStatus = data.getInt("sale_status");
                        if (indexPrice != Float.valueOf(data.getString("now_price")) && jsonArray.length() > 0) {
                            //倒计时
                            tolBuytime = info.getTolBuytime();
                            indexPrice = Float.valueOf(data.getString("now_price"));
                            llPrice.setNowPrice(getString(R.string.price_format, Float.valueOf(indexPrice)));
                            llPrice.setTime(Utils.countDown(tolBuytime));

                        }
                        String nowPrice = Utils.priceUnitFormat(this, indexPrice);
                        String nowOwner = data.getString("now_owner");
                        String tips;
                        if (saleStatus == 2) {
                            tips = getString(R.string.auction_detail_end_tips_format, nowOwner, nowPrice);
                            getDefaultHandler().removeCallbacks(countDownRun);
                            llPrice.setTime(Utils.countDown(0));
                        } else {
                            tips = getString(R.string.auction_detail_tips_format, nowOwner, nowPrice);
                            getDefaultHandler().removeCallbacks(countDownRun);
                            getDefaultHandler().postDelayed(countDownRun, 1000);

                            int sumTimes = data.getInt("sum_times");
                            int leftTimes = data.getInt("left_times");
                            setAutoOffer(leftTimes, sumTimes);
                        }
                        SpannableStringBuilder style = new SpannableStringBuilder(tips);
                        style.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)), tips.indexOf(nowOwner), tips.indexOf(nowOwner) + nowOwner.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        style.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)), tips.indexOf(nowPrice), tips.indexOf(nowPrice) + nowPrice.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        tvTips.setText(style);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_COLLECT_GOOD:
                try {
                    if (result.getInt("errcode") == 0) {
                        info.setIsCollected(1);
                        tvCollection.setText("收藏");
                        Drawable image = getResources().getDrawable(R.drawable.ic_collection_sel);
                        image.setBounds(0, 0, image.getMinimumWidth(), image.getMinimumHeight());
                        tvCollection.setCompoundDrawables(null, image, null, null);
                    }
//                    showToastSafe(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_DEL_COLLECT:
                try {
                    if (result.getInt("errcode") == 0) {
                        info.setIsCollected(0);
                        tvCollection.setText("收藏");
                        Drawable image = getResources().getDrawable(R.drawable.ic_collection_detail_def);
                        image.setBounds(0, 0, image.getMinimumWidth(), image.getMinimumHeight());
                        tvCollection.setCompoundDrawables(null, image, null, null);
                    }
//                    showToastSafe(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_GET_ONE_NEWEST:
                try {
                    if (result.getInt("errcode") == 0) {
                        if(isDestroyed())
                            return;
                        JSONObject data = result.getJSONObject("data");
                        String facePic = data.getString("face_pic");
                        String content = data.getString("content");
                        showNoticeAnim();
                        GlideUtils.loadAvatar(getApplicationContext(), facePic, ivNoticepic);
                        tvNoticeContent.setText(Html.fromHtml(content));
                        getDefaultHandler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                hideNoticeAnim();
                            }
                        },4000);
                    } else {
                        llNewsest.setVisibility(View.GONE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    llNewsest.setVisibility(View.GONE);
                }
                break;
        }
    }

    private void showNoticeAnim(){
        llNewsest.setVisibility(View.VISIBLE);
        Animation animation = new AlphaAnimation(0,1);
        animation.setDuration(800);
        llNewsest.startAnimation(animation);
    }

    private void hideNoticeAnim(){
        Animation animation = new AlphaAnimation(1,0);
        animation.setDuration(1000);
        llNewsest.startAnimation(animation);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                llNewsest.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    @Override
    protected void onFinish(HttpTag httpTag) {
        super.onFinish(httpTag);
        switch (httpTag) {
            case TAG_GOOD_DETAIL_INFO:
                setAuctionStatus();
                break;
            case TAG_GET_AUCTION_LOG://出价记录
                if (saleStatus == 1) {//1表示在拍，2表示竞拍结束
                    getDefaultHandler().removeCallbacks(auctionLogRun);
                    getDefaultHandler().postDelayed(auctionLogRun, postDelayed);
                } else {
                    getDefaultHandler().removeCallbacks(auctionLogRun);
                    HttpManager.getInstance(this).goodDetailInfo(indexGoodId, this);
                }

                break;
            case TAG_GET_ONE_NEWEST:
                getDefaultHandler().removeCallbacks(newestRun);
                getDefaultHandler().postDelayed(newestRun, 1000 * 5);
                break;
        }
    }

    @Override
    protected void onError(HttpTag httpTag, Call call, IOException e) {
        super.onError(httpTag, call, e);
        if (httpTag == HttpTag.TAG_GET_ONE_NEWEST)
            llNewsest.setVisibility(View.GONE);
    }

    @Override
    protected void onHandleMessage(Message msg) {
        super.onHandleMessage(msg);
        switch (msg.what) {
            case 10://竞拍倒计时更新UI
                tolBuytime--;
                llPrice.setTime(Utils.countDown(tolBuytime));
                if (tolBuytime > 1)
                    getDefaultHandler().postDelayed(countDownRun, 1000);
                break;
        }
    }


    /**
     * 轮询获取竞拍记录
     */
    private Runnable auctionLogRun = new Runnable() {
        @Override
        public void run() {
            getAuctionLog();
        }
    };

    /**
     * 倒计时
     */
    private Runnable countDownRun = new Runnable() {
        @Override
        public void run() {
            getDefaultHandler().sendEmptyMessage(10);

        }
    };

    private Runnable newestRun = new Runnable() {
        @Override
        public void run() {
            HttpManager.getInstance(GoodsDetailsActivity.this).getOneNewest(GoodsDetailsActivity.this);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getDefaultHandler().removeCallbacks(auctionLogRun);
        getDefaultHandler().removeCallbacks(countDownRun);
        Glide.with(getApplicationContext()).pauseRequests();
        getDefaultHandler().removeCallbacks(newestRun);
    }


}
